package com.nitty.cash.loop.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.view.View
import com.lib.common.permission.Permission
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiApplyBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.dialog.NittyGuideApplyDialog
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.ApplyPresenter
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.helper.TestAnalysisAddEvent
import com.nitty.cash.loop.utils.helper.TestDataLibInvoke
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import com.nitty.cash.loop.weight.ArcSeekBar
import org.json.JSONObject
import java.math.BigDecimal

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/9/25 19:21
 * @Annotation：申请贷款
 */
class ApplyAct: CommonActivity(),IViewContract.IApplyView {
    lateinit var binding: UiApplyBinding
    private var presenter: ApplyPresenter? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ApplyAct::class.java)
            context.startActivity(intent)
        }
    }

    override fun getNittyRootView(): View {
        binding = UiApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        NittyTitleBarUtil.setStatusBarLightMode(this, false)
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyTextTitle(getString(R.string.apply_title))
        setNittyTextTitleColor(Color.parseColor("#FFFFFFFF"))
        setNittyBackBtnRes(R.mipmap.img_back_white)
        setNittyRightBtnRes(R.mipmap.img_customer_white)
        setNittyRootParentBackgroundColors(Color.parseColor("#ffffd451"),Color.parseColor("#ffffac17"))

        initNittyRefreshLayout()
        binding.applyContentLayout.visibility = View.GONE
        binding.btnApplySubmit.isEnabled = false
//        binding.textApplyAmount.text = getApplyAvailableAmount()
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            val eventRemark = "LoanApply Page"
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,eventRemark)
        }
        binding.applySeekBar.setOnChangeListener(object : ArcSeekBar.OnChangeListener {
            override fun onStartTrackingTouch(isCanDrag: Boolean) {
            }
            override fun onProgressChanged(progress: Float, max: Float, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                binding.textApplyAmount.text = BigDecimal(showProcess.toString()).stripTrailingZeros().toPlainString()

            }
            override fun onStopTrackingTouch(isCanDrag: Boolean) {
                // 当用户结束触摸SeekBar（抬手）时调用
                if (isCanDrag){//滑动切换的时候才调试算接口
                    presenter?.requestApplyDataAction(false)
                }
            }
            override fun onSingleTapUp() {//点击切换进度回调
                // 当进度改变时调用
                val showProcess = binding.applySeekBar.progress * mScale + mMinProcess
                binding.textApplyAmount.text = BigDecimal(showProcess.toString()).stripTrailingZeros().toPlainString()
                presenter?.requestApplyDataAction(false)
            }
        })

        //提交
        binding.btnApplySubmit.setOnClickListener {
            showNittyLoading()
            presenter?.createApplyOrderAction()
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOAN_APPLY_SUBMIT,getApplyAmount())
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = ApplyPresenter(this)
        }
        showNittyLoading()
        presenter?.requestApplyDataAction()

        //上报 Battery 和 Wifi 信息
        TestDataLibInvoke.sycPhoneStateBatteryWifiData()
    }

    /* 初始化刷新 */
    private fun initNittyRefreshLayout() {
        binding.applyRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.applyRefreshLayout.setOnRefreshListener {
            presenter?.requestApplyDataAction()
        }
    }

    /**
     * 获取贷款金额
     */
    override fun getApplyAmount(): String {
        return binding.textApplyAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getApplyDays(): String {
        return ""
    }

    /**
     * 不可选择贷款额度
     */
    override fun showNotOptionalViews() {
        binding.applySeekBar.isEnabledDrag = false
        //动画效果
        binding.applySeekBar.showAnimation(0, binding.applySeekBar.max, 1000)
        //设置游标
        binding.applySeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_normal))
    }

    /**
     * 允许选择贷款额度
     */
    override fun showOptionalViews(data: JSONObject,showAnim: Boolean) {
        binding.applySeekBar.isEnabledDrag = true

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.applySeekBar.progress = showAmount

        if (showAnim){
            //动画效果
            binding.applySeekBar.showAnimation(0, binding.applySeekBar.progress, 1000)
        }
        //设置游标
        binding.applySeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_pressed))
        //显示引导dialog
        showApplyGuideDialog(data)
    }

    /**
     * 设置贷款明细
     */
    override fun showLoadDetailsList(data: JSONObject) {
        binding.applyContentLayout.visibility = View.VISIBLE
        binding.btnApplySubmit.isEnabled = true

        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        mMinProcess = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        //最大值为剩余额度
        val maxAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString()
//        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
//        mMinProcess = getApplyMinAmount().toInt()
//        val maxAmount = getApplyAvailableAmount()
        //颗粒度
        mScale = data.optInt("granularity")

        //设置最大值
        val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
        binding.applySeekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.applySeekBar.progress = showAmount

        binding.textApplyAmount.text = amount
        binding.textApplyMinAmount.text = mMinProcess.toString()
        binding.textApplyMaxAmount.text = maxAmount
        binding.textApplyDays.text = String.format(getString(R.string.apply_repay_days),data.optString("days"))

        val detailItemList = data.optJSONArray("detailItemList")
        if (detailItemList != null){
            if (detailItemList.length() >=1){
                val item = detailItemList.optJSONObject(0)
                binding.textApplyItemTitle1.text = item.optString("showName")
                binding.textApplyItemValue1.text = item.optString("showDetail")
            }
            if (detailItemList.length() >= 3){
                val item = detailItemList.optJSONObject(2)
                binding.textApplyItemTitle2.text = item.optString("showName")
                binding.textApplyItemValue2.text = item.optString("showDetail")
            }
            if (detailItemList.length() >= 4){
                val item = detailItemList.optJSONObject(3)
                binding.textApplyItemTitle3.text = item.optString("showName")
                binding.textApplyItemValue3.text = item.optString("showDetail")
            }
            if (detailItemList.length() >= 5){
                val item = detailItemList.optJSONObject(4)
                binding.textApplyItemTitle4.text = item.optString("showName")
                binding.textApplyItemValue4.text = item.optString("showDetail")
            }
            if (detailItemList.length() >= 7){
                val item = detailItemList.optJSONObject(6)
                binding.textApplyItemTitle5.text = item.optString("showName")
                binding.textApplyItemValue5.text = item.optString("showDetail")
            }
        }
    }

    /**
     * 贷款申请成功
     */
    override fun showLoanApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //刷新订单列表
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_REFRESH))

        //是否包含SMS权限
        val permissionList = NittyConfigsHelper.getNittyPermissionsList()
        if (permissionList.contains(Permission.READ_SMS)){
            //进入SMS权限使用说明页面
            onIntent(SmsUploadAct::class.java)
            finish()
        } else {
            //刷新主流程
            publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
        }
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showLoanApplyFailed() {
        hiddenNittyLoading()
        finish()
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.applyRefreshLayout.isRefreshing = false
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        when(event.eventType){
            NittyEventData.TYPE.NITTY_PROCESS_REFRESHED -> {
                //需要校验 WhatsApp 或 SMS
                if (NittyProcessHelper.isCheckWhatsApp() || NittyProcessHelper.isCheckSMS()){
                    CheckAct.start(this)
                }
                finish()
            }
            else -> {

            }
        }
    }

    /**
     * 展示引导dialog
     */
    private fun showApplyGuideDialog(data: JSONObject){
        val isShowGuide = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_DIALOG_GUIDE_APPLY_SHOW)
        if (isShowGuide){//已显示过
            return
        }
        binding.applySeekBar.visibility = View.INVISIBLE
        binding.textApplyAmount.visibility = View.INVISIBLE
        binding.textApplyMinAmount.visibility = View.INVISIBLE
        binding.textApplyMaxAmount.visibility = View.INVISIBLE
        NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_DIALOG_GUIDE_APPLY_SHOW,true)
        val dialog = NittyGuideApplyDialog(this,object: NittyGuideApplyDialog.IDialogCallback{
            override fun onClick(view: View?) {
                binding.applySeekBar.visibility = View.VISIBLE
                binding.textApplyAmount.visibility = View.VISIBLE
                binding.textApplyMinAmount.visibility = View.VISIBLE
                binding.textApplyMaxAmount.visibility = View.VISIBLE
            }
        })
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showNittyApplyGuideDatas(data)
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOAN_APPLY_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOAN_APPLY_END)
    }
}